package com.voicechat.firstmet.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.utils.AudioRecorderUtil;
import com.voicechat.firstmet.utils.CheckAudioPermission;
import com.voicechat.firstmet.utils.ConstantSet;
import com.voicechat.firstmet.utils.FileUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.RecordTimerUtil;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: SetVoiceIntroduceActivity
 * @Description: 设置语音介绍页面
 * @Author: ljp
 * @CreateDate: 2018/9/19 17:08
 * @Version: 1.0
 */
public class SetVoiceIntroduceActivity extends BaseActivity {
    @BindView(R.id.image_open)
    ImageView imageOpen;
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.horizontal_scrollview)
    HorizontalScrollView horizontalScrollview;
    @BindView(R.id.image_sound)
    ImageView imageSound;
    @BindView(R.id.tv_recording)
    TextView tvRecording;
    @BindView(R.id.linear_voice_time)
    LinearLayout linearVoiceTime;
    @BindView(R.id.tv_voice_time)
    TextView tvVoiceTime;
    @BindView(R.id.linear_voice_play)
    LinearLayout linearVoicePlay;
    @BindView(R.id.image_sound2)
    ImageView imageSound2;
    @BindView(R.id.image_set_voice)
    ImageView imageSetVoice;
    //播放音频
    private MediaUtil mediaUtil;
    //录制完成音频地址
    private String audioFilePath;
    private String TAG = "SetVoiceIntroduceActivity";
    //录制音频
    private AudioRecorderUtil audioRecorderUtil;
    //录制音频时间倒计时
    private RecordTimerUtil recordTimerUtil;
    View view;
    //上传oss返回地址
    private String ossVoiceUrl;
    private String mobile;
    //录音文件保存名（手机号加上yinyin）
    private String recordPath;
    //本地录音文件
    private String voicePath;
    //声波动画移动的距离计算
    int i = 0;
    int length = 0;
    //是否取消保存录音
    private boolean isSure;
    private AnimationDrawable frameAnimatio;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0){
                toast_MakeText("保存成功");
                Intent intentTemp = new Intent();
                //返回路径
                intentTemp.putExtra("ossVoiceUrl",Utils.spitString(ossVoiceUrl));
                //音频的长度
                intentTemp.putExtra("time", mediaUtil.getDuration(audioFilePath)/1000+"");
                intentTemp.putExtra("voiceName", audioFilePath);
                Log.i(TAG, "handleMessage: ----"+audioFilePath);
                setResult(RESULT_OK, intentTemp);
                finish();
            }
        }
    };
    private MySelfInfoBean.ObjectBean mySeleInfo;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_set_voice;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        initView();
    }
    @Override
    protected void onStart() {
        super.onStart();
    }
    /**
     * @return
     * @method
     * @description 控件实例化
     * @date: 2018/9/28 18:57
     * @author: ljp
     */
    private void initView() {
        mediaUtil = MediaUtil.getInstance();
        mobile = SPUtils.getEditoString(SPUtils.SP_PHONE);
        recordPath = mobile + "yinyin.aac";
        view = View.inflate(context, R.layout.popu_voice_introduce, null);
        int srecchWidth = Utils.getSrecchWidth(context);
        i = srecchWidth / 100;
        length = 0;
        if(!TextUtils.isEmpty(mySeleInfo.getVoiceInfo())){
            if (FileUtils.isExists(ConstantSet.VOICE +ConstantSet.VOICEINTR_PATH+Utils.getVoiceName(mySeleInfo.getVoiceInfo()))) {
                linearVoicePlay.setVisibility(View.VISIBLE);
                linearVoiceTime.setVisibility(View.GONE);
                voicePath = ConstantSet.VOICE +ConstantSet.VOICEINTR_PATH+ Utils.getVoiceName(mySeleInfo.getVoiceInfo());
                //Log.i(TAG, "initView: -----"+voicePath);
                tvVoiceTime.setText(mySeleInfo.getDuration() + "”");
            } else {
                linearVoicePlay.setVisibility(View.GONE);
                linearVoiceTime.setVisibility(View.VISIBLE);
            }
        }else {
            linearVoicePlay.setVisibility(View.GONE);
            linearVoiceTime.setVisibility(View.VISIBLE);
        }
        recordTimerUtil = new RecordTimerUtil(60, tvTime, activity);
        audioRecorderUtil = new AudioRecorderUtil(ConstantSet.VOICE+ConstantSet.VOICEINTR_PATH);
        progressBar.setMax(60);
        horizontalScrollview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                return true;
            }
        });
        if(Build.VERSION.SDK_INT < 23){
            if(CheckAudioPermission.isHasPermission(context)){
                setTouchListener();
            }else {
                ActivityCompat.requestPermissions(activity, new String[]{
                        Manifest.permission.RECORD_AUDIO}, 1);
            }
        }else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.RECORD_AUDIO}, 1);
            } else {
                setTouchListener();
            }
        }
    }
    private void setTouchListener() {
        imageOpen.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int start_x = 0, start_y = 0, end_x, end_y, mov_x, mov_y;
                // 停止播放
                if (mediaUtil != null) {
                    mediaUtil.stop();
                }
                // 处理动作
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        recordTimerUtil.isSure = false;
                        //开始录制  显示倒计时页面
                        linearVoicePlay.setVisibility(View.GONE);
                        linearVoiceTime.setVisibility(View.VISIBLE);
                        audioRecorderUtil.start(recordPath);
                        imageOpen.setImageResource(R.mipmap.record_down);
                        recordTimerUtil.start();
                        tvRecording.setText("上滑删除");
                        showRecordVoicePopu(0);
                        isSure = false;
                        break;
                    case MotionEvent.ACTION_UP:
                        if (PopUtils.isPopShowing()) {
                            PopUtils.hidePopupWindow();
                        }
                        tvRecording.setText("长按录制");
                        imageOpen.setImageResource(R.mipmap.record);
                        long time = audioRecorderUtil.getSumTime();
                        end_x = (int) event.getX();
                        end_y = (int) event.getY();
                        mov_x = Math.abs(start_x - end_x);
                        mov_y = Math.abs(start_y - end_y);
                        Log.i(TAG, "onTouch: ---mov_x--"+mov_x+"--mov_y--"+mov_y);
                        if (mov_x > 200 || mov_y > 200) {
                            recordTimerUtil.isSure = true;
                            isSure = true;
                            progressBar.setProgress(0);
                            //上划取消
                            audioRecorderUtil.cancel();
                            // 取消录音（不保存录音文件）
                            audioRecorderUtil.stop();
                            recordTimerUtil.onFinish();
                            audioFilePath = "";
                        } else {
                            if (time < 5000) {
                                audioRecorderUtil.cancel();
                                Toast.makeText(context, "录音时间太短,请重新录制", Toast.LENGTH_SHORT).show();
                                if(voicePath == null){
                                    tvTime.setText("60");
                                }else {
                                    linearVoicePlay.setVisibility(View.VISIBLE);
                                    linearVoiceTime.setVisibility(View.GONE);
                                    tvVoiceTime.setText(MediaUtil.getInstance().getDuration(voicePath)/1000 + "”");
                                }
                                progressBar.setProgress(0);
                                recordTimerUtil.onFinish();
                                audioFilePath = "";
                            } else {
                                recordTimerUtil.onFinish();
                                audioRecorderUtil.stop();
                                // Log.i(TAG, "onTouch: ------up-----------");
                            }
                        }
                    case MotionEvent.ACTION_CANCEL:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        end_x = (int) event.getX();
                        end_y = (int) event.getY();
                        mov_x = Math.abs(start_x - end_x);
                        mov_y = Math.abs(start_y - end_y);
                        // Log.i(TAG, "onTouch: -----ACTION_MOVE-----"+mov_x+"--mov_y---"+mov_y);
                        if (mov_x > 200 || mov_y > 200) {
                            //Log.i("******mov_x,y", String.valueOf(mov_x) + "；" + String.valueOf(mov_y));
                            showRecordVoicePopu(1);
                        } else if (mov_x < 200 || mov_y < 200) {
                            showRecordVoicePopu(0);
                        }
                        break;
                }
                return true;
            }
        });
    }

    /**
     * ⑨重写onRequestPermissionsResult方法
     * 获取动态权限请求的结果,再开启录制音频
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //setTouchListener();
        } else {
            Toast.makeText(this, "用户拒绝了权限", Toast.LENGTH_SHORT).show();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //pop 的录制中动画图片
    ImageView imageRecording;
    //pop  录制中显示布局
    LinearLayout linearRecordOn;
    //pop  上滑时显示布局
    LinearLayout linearRecordUp;

    /**
     * @return flay判断是上滑还是长按录制中
     * @method
     * @description 按住上滑弹出popu布局
     * @date: 2018/9/28 19:11
     * @author: ljp
     */
    private void showRecordVoicePopu(int flag) {
        imageRecording = view.findViewById(R.id.image_recording);
        linearRecordOn = view.findViewById(R.id.linear_record_on);
        ImageView imageRecordCacel = view.findViewById(R.id.image_record_cacel);
        linearRecordUp = view.findViewById(R.id.linear_record_up);
        if (!PopUtils.isPopShowing()) {
            PopUtils.showPopupWindowRecprd(activity, view, true);
            linearRecordOn.setVisibility(View.VISIBLE);
        } else {
            if (flag == 0) {//按下时布局
                linearRecordOn.setVisibility(View.VISIBLE);
                linearRecordUp.setVisibility(View.GONE);
            } else {
                linearRecordOn.setVisibility(View.GONE);
                linearRecordUp.setVisibility(View.VISIBLE);
            }
        }
        audioRecorderUtil.setOnAudioStatusUpdateListener(new AudioRecorderUtil.OnAudioStatusUpdateListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onProgress(double db, long time) {
                if (Integer.parseInt(Utils.long2String(time)) >= 61) {
                    audioRecorderUtil.stop();
                    //tvTime.setText("60");
                    recordTimerUtil.onFinish();
                    progressBar.setProgress(60);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        progressBar.setProgress(Integer.parseInt(Utils.long2String(time)), true);
                    }else {
                        progressBar.setProgress(Integer.parseInt(Utils.long2String(time)));
                    }
                    horizontalScrollview.smoothScrollTo(length, 0);
                    length = length + i;
                    imageRecording.setImageLevel((int) db);
                }
            }

            @Override
            public void onError(Exception e) {
            }

            @Override
            public void onCancel() {
                // Log.i(TAG, "onStop: ---isSure-----"+isSure+"------audioFilePath----"
                //        +TextUtils.isEmpty(voicePath)+"---audioFilePath---"+voicePath);
                if (isSure) {
                    //取消保存
                    if (!TextUtils.isEmpty(voicePath)) {
                        linearVoicePlay.setVisibility(View.VISIBLE);
                        linearVoiceTime.setVisibility(View.GONE);
                        tvVoiceTime.setText(mediaUtil.getDuration(voicePath)/1000 + "”");
                    } else {
                        linearVoicePlay.setVisibility(View.GONE);
                        linearVoiceTime.setVisibility(View.VISIBLE);
                        tvTime.setText("60");
                    }
                }
            }

            @Override
            public void onStop(String filePath) {
                Log.i(TAG, "onStop: -------------"+filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    audioFilePath = filePath;
                    linearVoicePlay.setVisibility(View.VISIBLE);
                    linearVoiceTime.setVisibility(View.GONE);
                    tvVoiceTime.setText(mediaUtil.getDuration(audioFilePath)/1000 + "”");
                } else {
                    if (!TextUtils.isEmpty(voicePath)) {
                        linearVoicePlay.setVisibility(View.VISIBLE);
                        linearVoiceTime.setVisibility(View.GONE);
                        tvVoiceTime.setText(mediaUtil.getDuration(voicePath)/1000 + "”");
                    }
                }
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
                // TODO 上传音频文件
            }
        });
    }

    private void setVoice(){

    }

    @OnClick({R.id.linear_back, R.id.tv_save, R.id.image_open, R.id.linear_voice_play})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            //保存 上传至服务器
            case R.id.tv_save:
                if(!TextUtils.isEmpty(audioFilePath)){
                    setOssVoice(audioFilePath);
                }else {
                    toast_MakeText("您还没有录音哦!");
                }
                break;
            //录制按钮
            case R.id.image_open:
                break;
            //播放按钮
            case R.id.linear_voice_play:
                imageSetVoice.setImageResource(0);
                imageSetVoice.setBackgroundResource(R.drawable.set_voice);
                frameAnimatio = (AnimationDrawable) imageSetVoice.getBackground();
                try {
                    player();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * @return
     * @method
     * @description 播放语音
     * @date: 2018/9/28 18:57
     * @author: ljp
     */
    private void player() throws FileNotFoundException {
        String path;
        if(TextUtils.isEmpty(audioFilePath)){
            path = voicePath;
        }else {
            path = audioFilePath;
        }
       // Log.i(TAG, "player: ---voicePath--"+voicePath);
       // Log.i(TAG, "player: ---audioFilePath--"+audioFilePath);
        if (TextUtils.isEmpty(path)) {
            return;
        }
        if (mediaUtil == null) {
            mediaUtil = MediaUtil.getInstance();
            mediaUtil.play(new FileInputStream(path));
            frameAnimatio.start();
        } else {
            if (mediaUtil.setPlayer()) {
                mediaUtil.stop();
                frameAnimatio.stop();
                imageSetVoice.setBackgroundResource(0);
                imageSetVoice.setImageResource(R.mipmap.set_voice_play3);
            } else {
                mediaUtil.play(new FileInputStream(path));
                imageSetVoice.setImageResource(0);
                imageSetVoice.setBackgroundResource(R.drawable.set_voice);
                frameAnimatio = (AnimationDrawable) imageSetVoice.getBackground();
                frameAnimatio.start();
            }
        }
        mediaUtil.setEventListener(new MediaUtil.EventListener() {
            @Override
            public void onStop() {
                frameAnimatio.stop();
                imageSetVoice.setBackgroundResource(0);
                imageSetVoice.setImageResource(R.mipmap.set_voice_play3);
            }
        });
    }
    @Override
    protected void onPause() {
        super.onPause();
        if(frameAnimatio != null){
            frameAnimatio.stop();
            frameAnimatio.selectDrawable(2);
        }
    }

    /**
     * @return
     * @method
     * @description 上传录音到oss服务器
     * @date: 2018/9/25 15:54
     * @author: ljp
     */
    private void setOssVoice(String voice) {
        String name = mobile + "yinyin";
        new Thread(new Runnable() {
            @Override
            public void run() {
                OssClient.getInstance().init(context).
                        upload(name, voice, OssConfig.VOICE, new OssClient.OnUploadFile() {
                            @Override
                            public void onUploadFileSuccess(String info) {
                                Log.i(TAG, "onUploadFileSuccess: -----"+info);
                                ossVoiceUrl = info;
                                Message msg = Message.obtain();
                                msg.what = 0;
                                handler.sendMessage(msg);
                            }
                            @Override
                            public void onUploadFileFailed(String errCode) {
                            }
                        });
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaUtil.getInstance().stop();
    }
}
